package net.sh.dpinfrastructure.mail;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import net.sh.dpinfrastructure.config.DPConfig;
import net.sh.dpinfrastructure.exception.DPException;
import net.sh.dpinfrastructure.log.DPLogger;

public class DPSpringMail implements DPMail {

    private static final DPLogger LOGGER = new DPLogger(DPMail.class);
    
    private JavaMailSenderImpl mailSender;
    
    /**
     * 发件人
     */
    private String from;
    
    public DPSpringMail(DPConfig config) {
        Properties props = new Properties();
        // 邮箱服务器地址
        String host = config.get("mail.host");
        // 用户名
        final String username = config.get("mail.username");
        // 密码
        final String password = config.get("mail.password");
        
        if (StringUtils.isBlank(host) || StringUtils.isBlank(username) || StringUtils.isBlank("password")) {
            throw new DPException("配置缺失");
        }
        props.put("mail.smtp.host", host);
        //是否开启验证
        props.put("mail.smtp.auth", config.getBoolValue("mail.auth", false));
        //邮箱协议
        props.put("mail.transport.protocol", config.get("mail.protocol", "smtp"));  
        
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        mailSender = new JavaMailSenderImpl();
        mailSender.setSession(session);
        String nickname = config.get("mail.nickname");
        if (StringUtils.isBlank(nickname)) {
            from = config.get("mail.sender");
        } else {
            try {
                from = MimeUtility.encodeText(nickname) + "<" + config.get("mail.sender") + ">";
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                throw new DPException("创建发件人失败", e);
            }
        }
        LOGGER.debug("mail对话创建成功");
    }

    @Override
    public void sendSimpleMail(Set<String> recipients, String title, String msg) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setTo(recipients.toArray(new String[] {}));
            message.setSubject(title);
            message.setFrom(from);
            message.setText(msg);
            mailSender.send(message);
        } catch (Exception e) {
            throw new DPException("邮件发送失败", e);
        }
    }

    @Override
    public void sendComplexMail(Set<String> recipients, String title, String msg, List<File> attachments) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message, true, "utf-8");  
            messageHelper.setTo(recipients.toArray(new String[] {}));
            messageHelper.setFrom(from);
            messageHelper.setSubject(title);  
            messageHelper.setText(msg, true);
            if (CollectionUtils.isNotEmpty(attachments)) {
                for (File attachment : attachments) {
                    messageHelper.addAttachment(attachment.getName(), attachment);
                }
            }
            mailSender.send(message);
        } catch (Exception e) {
            throw new DPException("邮件发送失败", e);
        }
    }
}
